﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'daily_events_state.dart';
import 'event_selection_view.dart';
import '../../../entity/daily_events_models.dart';
import 'package:azring/core/repository/default_api.dart';

/// 今日事件控制器
class DailyEventsLogic extends GetxController {
  final DailyEventsState state = DailyEventsState();

  /// 自定义事件输入框控制器
  late final TextEditingController customEventController;

  /// 已选择的标签
  RxList<String> get selectedTags => state.selectedTags;

  /// 自定义事件文本
  RxString get customEventText => state.customEventText;

  /// 获取格式化的当前日期
  String getCurrentDate() {
    final now = DateTime.now();
    return '${now.year}年${now.month.toString().padLeft(2, '0')}月${now.day.toString().padLeft(2, '0')}日';
  }

  /// 切换标签选择状态
  void toggleTag(String tag) {
    if (selectedTags.contains(tag)) {
      selectedTags.remove(tag);
    } else {
      selectedTags.add(tag);
    }
  }

  /// 添加自定义标签
  void addCustomTag(String tag) {
    if (!selectedTags.contains(tag)) {
      selectedTags.add(tag);
    }
  }

  /// 添加标签到服务器
  Future<bool> addTagToServer(String tagName, int tagType) async {
    try {
      await DefaultApi().addDailyTagPost<Map<String, dynamic>>(
        tagType: tagType.toString(),
        tagName: tagName,
      );
      await fetchTagData();
      return true;
    } catch (e) {
      print('添加标签失败: $e');
      Toast.show('添加标签失败');
      return false;
    }
  }

  /// 根据sectionType获取对应的tagType
  int getTagTypeBySectionType(String? sectionType) {
    switch (sectionType) {
      case 'dailyCheckIn':
        return 1; // 推荐打卡事项
      case 'entertainment':
        return 2; // 娱乐活动
      case 'symptoms':
        return 3; // 症状
      default:
        return 1; // 默认推荐打卡事项
    }
  }


  /// 添加事件到指定类别
  void addEvent(String category, String event) {
    RxList<String> targetList;
    switch (category) {
      case 'dailyCheckIn':
        targetList = state.dailyCheckInEvents;
        break;
      case 'entertainment':
        targetList = state.entertainmentEvents;
        break;
      case 'symptoms':
        targetList = state.symptomsEvents;
        break;
      default:
        return;
    }

    // 检查是否超过最大记录数量
    if (targetList.length >= DailyEventsState.maxRecordCount) {
      Toast.show('最多只能记录${DailyEventsState.maxRecordCount}条事件');
      return;
    }

    if (!targetList.contains(event)) {
      targetList.add(event);
    }
  }

  /// 移除事件
  void removeEvent(String category, String event) {
    RxList<String> targetList;
    switch (category) {
      case 'dailyCheckIn':
        targetList = state.dailyCheckInEvents;
        break;
      case 'entertainment':
        targetList = state.entertainmentEvents;
        break;
      case 'symptoms':
        targetList = state.symptomsEvents;
        break;
      default:
        return;
    }

    targetList.remove(event);
  }

  /// 获取指定类别的显示事件列表
  List<String> getDisplayEvents(String category) {
    RxList<String> targetList;

    switch (category) {
      case 'dailyCheckIn':
        targetList = state.dailyCheckInEvents;
        break;
      case 'entertainment':
        targetList = state.entertainmentEvents;
        break;
      case 'symptoms':
        targetList = state.symptomsEvents;
        break;
      default:
        return [];
    }

    if (targetList.length <= DailyEventsState.maxDisplayCount) {
      return targetList.toList();
    } else {
      return targetList.take(DailyEventsState.maxDisplayCount).toList();
    }
  }

  /// 检查是否需要显示"显示更多"按钮
  bool shouldShowMoreButton(String category) {
    RxList<String> targetList;

    switch (category) {
      case 'dailyCheckIn':
        targetList = state.dailyCheckInEvents;
        break;
      case 'entertainment':
        targetList = state.entertainmentEvents;
        break;
      case 'symptoms':
        targetList = state.symptomsEvents;
        break;
      default:
        return false;
    }

    return targetList.length > DailyEventsState.maxDisplayCount;
  }

  void onShowMoreTap(String category) {
    String title;
    switch (category) {
      case 'dailyCheckIn':
        title = '当前健康计划推荐打卡事项';
        break;
      case 'entertainment':
        title = '你今天有什么娱乐活动？';
        break;
      case 'symptoms':
        title = '你今天有什么症状？';
        break;
      default:
        return;
    }

    Get.to(() => EventSelectionView(
          category: category,
          title: title,
        ));
  }

  /// 获取今日事件数据
  void fetchTodayEvents() {}

  /// 获取标签数据
  Future<void> fetchTagData() async {
    try {
      state.isLoading.value = true;

      final response =
          await DefaultApi().queryDailyTagsListGet<List<dynamic>>();
      if (response != null) {
        final tagGroups = response
            .map((json) => TagGroup.fromJson(json as Map<String, dynamic>))
            .toList();
        state.tagGroups.value = tagGroups;
        // 根据tagType更新各部分的事件数据
        _updateEventsFromTagData();
      } else {
        state.tagGroups.clear();
      }
    } catch (e) {
      Toast.show('获取标签数据失败');
      state.tagGroups.clear();
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 根据标签数据更新各部分事件
  void _updateEventsFromTagData() {
    for (final tagGroup in state.tagGroups) {
      if (tagGroup.tagInfos != null) {
        final tagNames = tagGroup.tagInfos!
            .map((tag) => tag.tagName ?? '')
            .where((name) => name.isNotEmpty)
            .toList();
        switch (tagGroup.tagType) {
          case 1: // 推荐打卡事项
            state.dailyCheckInEvents.clear();
            state.dailyCheckInEvents.addAll(tagNames);
            break;
          case 2: // 娱乐活动
            state.entertainmentEvents.clear();
            state.entertainmentEvents.addAll(tagNames);
            break;
          case 3: // 症状
            state.symptomsEvents.clear();
            state.symptomsEvents.addAll(tagNames);
            break;
        }
      }
    }
  }

  /// 获取指定类型的标签数据
  List<String> getTagNamesByType(int tagType) {
    final tagGroup =
        state.tagGroups.firstWhereOrNull((group) => group.tagType == tagType);
    if (tagGroup?.tagInfos != null) {
      return tagGroup!.tagInfos!
          .map((tag) => tag.tagName ?? '')
          .where((name) => name.isNotEmpty)
          .toList();
    }
    return [];
  }

  /// 获取指定类型的前N个标签
  List<String> getTagNamesByTypeLimit(int tagType, int limit) {
    final allTags = getTagNamesByType(tagType);
    return allTags.take(limit).toList();
  }

  /// 保存事件
  Future<void> saveEvent() async {
    final selectedTagsList = selectedTags.toList();
    final customText = customEventText.value;

    print('保存事件: 标签=$selectedTagsList, 自定义文本=$customText');

    try {
      // 准备提交数据
      await submitDailyEvents();

      // 显示保存成功提示
      Toast.show('今日事件已保存');
    } catch (e) {
      print('保存事件失败: $e');
      Toast.show('保存失败，请重试');
    }
  }

  /// 提交今日事件数据
  Future<void> submitDailyEvents() async {
    try {
      // 收集各类型的事件数据
      final entertainmentTags = state.entertainmentEvents.join(', ');
      final symptomsTags = state.symptomsEvents.join(', ');
      final customEvent = customEventText.value;

      // 调用API提交数据
      final response =
          await DefaultApi().addDailyTagsPost<Map<String, dynamic>>(
        gameThing: entertainmentTags.isNotEmpty ? entertainmentTags : null,
        symptomThing: symptomsTags.isNotEmpty ? symptomsTags : null,
        eventInfo: customEvent.isNotEmpty ? customEvent : null,
      );

      if (response != null) {
        print('提交今日事件成功: $response');
      } else {
        throw Exception('API响应为空');
      }
    } catch (e) {
      print('提交今日事件失败: $e');
      rethrow;
    }
  }

  /// 请求AI评分
  Future<Map<String, dynamic>> requestAiScore() async {
    try {
      // 收集用户实际选择的标签数据
      final selectedTagsList = selectedTags.toList();
      final eventInfo = customEventText.value;
      
      // 根据选择的标签分类
      String? recommendItems;
      String? gameThing;
      String? symptomThing;
      
      for (final tag in selectedTagsList) {
        // 检查标签属于哪个类别
        if (state.dailyCheckInEvents.contains(tag)) {
          recommendItems = (recommendItems ?? '') + (recommendItems != null ? ', ' : '') + tag;
        } else if (state.entertainmentEvents.contains(tag)) {
          gameThing = (gameThing ?? '') + (gameThing != null ? ', ' : '') + tag;
        } else if (state.symptomsEvents.contains(tag)) {
          symptomThing = (symptomThing ?? '') + (symptomThing != null ? ', ' : '') + tag;
        }
      }
      
      // 调用API提交数据并获取AI评分
      final response = await DefaultApi().addDailyTagsPost<Map<String, dynamic>>(
        gameThing: gameThing,
        recommendItems: recommendItems,
        symptomThing: symptomThing,
        eventInfo: eventInfo.isNotEmpty ? eventInfo : null,
      );
      
      if (response != null) {
        print('AI评分请求成功: $response');
        
        // 从响应中提取AI评分数据
        return {
          'score': response['data']['recordScores'] ?? 5,
          'event': response['data']['eventInfo'] ?? eventInfo,
          'aiComment': response['data']['aiCcomments'] ?? 'AI正在分析您的数据...',
          'rawResponse': response['data'], // 保存原始响应数据用于记录
        };
      } else {
        throw Exception('AI评分API响应为空');
      }
    } catch (e) {
      print('AI评分请求失败: $e');
      // 返回默认值
      return {
        'score': 5,
        'event': customEventText.value.isNotEmpty ? customEventText.value : '暂无事件记录',
        'aiComment': 'AI分析暂时不可用，请稍后重试。',
        'rawResponse': null,
      };
    }
  }

  /// 记录AI评分结果
  Future<bool> recordAiScore(Map<String, dynamic> aiData) async {
    try {
      final rawResponse = aiData['rawResponse'] as Map<String, dynamic>?;
      if (rawResponse == null) {
        print('没有可记录的数据');
        return false;
      }

      // 调用更新接口记录AI评分结果
      final response = await DefaultApi().updateDailyTagsPost<Map<String, dynamic>>(
        id: rawResponse['id'],
        gameThing: rawResponse['gameThing'],
        recommendItems: rawResponse['recommendItems'],
        symptomThing: rawResponse['symptomThing'],
        eventInfo: rawResponse['eventInfo'],
        recordScores: rawResponse['recordScores']?.toString(),
        aiCcomments: rawResponse['aiCcomments'],
      );

      if (response != null) {
        print('记录AI评分成功: $response');
        Toast.show('记录成功');
        return true;
      } else {
        Toast.show('记录失败，请重试');
        return false;
      }
    } catch (e) {
      print('记录AI评分失败: $e');
      Toast.show('记录失败，请重试');
      return false;
    }
  }

  /// 根据选中的标签生成文字描述
  String _generateTextFromSelectedTags() {
    if (selectedTags.isEmpty) {
      return '';
    }

    // 分类标签
    final healthTags = <String>[];
    final entertainmentTags = <String>[];
    final symptomTags = <String>[];

    for (final tag in selectedTags) {
      if (state.dailyCheckInEvents.contains(tag)) {
        healthTags.add(tag);
      } else if (state.entertainmentEvents.contains(tag)) {
        entertainmentTags.add(tag);
      } else if (state.symptomsEvents.contains(tag)) {
        symptomTags.add(tag);
      }
    }

    // 生成文字描述
    final parts = <String>[];
    if (healthTags.isNotEmpty) {
      parts.add('打卡事项有：${healthTags.join('、')}');
    }
    if (entertainmentTags.isNotEmpty) {
      parts.add('娱乐活动有：${entertainmentTags.join('、')}');
    }
    if (symptomTags.isNotEmpty) {
      parts.add('症状有：${symptomTags.join('、')}');
    }

    return parts.join('；');
  }

  @override
  void onInit() {
    super.onInit();
    // 初始化自定义事件输入框控制器
    customEventController = TextEditingController(text: customEventText.value);
    
    // 监听文本变化并同步到状态
    customEventController.addListener(() {
      customEventText.value = customEventController.text;
    });

    // 监听选中标签的变化，自动更新输入框内容
    ever(selectedTags, (_) {
      final generatedText = _generateTextFromSelectedTags();
      customEventController.text = generatedText;
      customEventText.value = generatedText;
    });
    
    fetchTodayEvents();
    fetchTagData(); // 获取标签数据
  }

  @override
  void onClose() {
    // 释放控制器资源
    customEventController.dispose();
    super.onClose();
  }
}
